package org.ctgu.service.impl;

import org.ctgu.Exception.BaseException;
import org.ctgu.entity.User;
import org.ctgu.entity.dto.UserDTO;
import org.ctgu.mapper.UserMapper;
import org.ctgu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userDTO
     */
    public User login(UserDTO userDTO) {
        // 获取用户名，密码和用户角色
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        Integer role = userDTO.getRole();

        // 根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        // 处理异常情况
        // 用户为空
        if (user == null) {
            throw new BaseException("该用户未注册");
        }
        // 密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            throw new BaseException("密码错误");
        }
        return user;
    }

    /**
     * 用户注册
     * @param userDTO
     */
    public void register(UserDTO userDTO) {
        // 判断用户是否存在
        User oldUser = userMapper.getByUsername(userDTO.getUsername());
        if (oldUser != null) {
            throw new BaseException("用户名已存在");
        }
        // 将密码加密后保存到数据库
        String password = userDTO.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        User newUser = User.builder()
                .username(userDTO.getUsername())
                .password(password)
                .role(0)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        userMapper.insert(newUser);
    }

}









